package com.gugee.notice.core;

import cn.hutool.http.HttpUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gugee.notice.config.AppConfig;
import com.xiguaji.boot.toolkit.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class Notice {

    @Autowired
    AppConfig appConfig;


    public String sendDingNotice(List<String> mobileList,String content){
        try {

            //群机器人复制到的秘钥secret
            String secret = appConfig.getDingRobotSecret();
            //获取系统时间戳
            Long timestamp = System.currentTimeMillis();
            //拼接
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign，可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址（配置机器人的webhook）
            // String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=e3e43dbdfeea1dc9e8ac87d6160ef69eeb3206100ab20891c3949de1e14d9771&timestamp=" + timestamp + "&sign=" + sign;
            String dingUrl = appConfig.getDingRobotUrl()+"&timestamp=" + timestamp + "&sign=" + sign;


            //是否通知所有人
//            boolean isAtAll = true;
            //通知具体人的手机号码列表
            //组装请求内容
            String reqStr = buildReqStr(content, false, mobileList);

            //推送消息（http请求）
            String result = HttpUtil.post(dingUrl, reqStr);
            // String result = HttpClientUtil.sendPostDataByJson(sign, reqStr,"utf8");
            System.out.println("result == " + result);

        } catch (Exception e) {
            log.error("钉钉发送失败！",e);
            return "钉钉发送失败";
        }
        return "钉钉通知发送成功";
    }

    /**
     * 组装请求报文
     * @param content
     * @return
     */
    private String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        if(!isAtAll){
            for(String mobile:mobileList){
                content=content+"@"+mobile;
            }
        }
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JsonUtil.parseJson(reqMap);
    }


}
